Representing Connections in a Graph
Graphs are abstract structures of nodes and edges. To use them in a program, we need concrete data structures. The two most common are Adjacency Lists and Adjacency Matrices, each with distinct trade-offs.
- Adjacency List: An array where each index corresponds to a vertex. The element at that index is a list of all vertices it connects to.
- Pros: Space-efficient for sparse graphs (few edges), with space complexity of . Iterating over a vertex's neighbors is fast.
- Cons: Checking for a specific edge can be slow, taking up to time.
- Adjacency Matrix: A matrix where cell is 1 if an edge exists from vertex to , and 0 otherwise.
- Pros: Extremely fast edge lookup, taking time. Well-suited for dense graphs (many edges).
- Cons: Requires space regardless of the number of edges, which is very inefficient for sparse graphs.
📝 Interactive Quiz
1. What is the time complexity to check if an edge exists between two vertices in an Adjacency Matrix?
2. What is the space complexity of an Adjacency List for a graph with vertices and edges?
3. For which type of graph is an Adjacency Matrix generally more space-efficient?
4. You are modeling a social network with millions of users but relatively few connections per user. Which representation is better?